#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param upload);
use SIM_settings;
use SIM_base;
use SIM_nodeInfo;
use SIM_cgiSettings;
use SIM_updateInfo;

# Startupscript casetool, part of Sipman.

my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];


my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $updateTool = $ENV{'SIM_UPDATET'} || die "No env SIM_UPDATET found.";
my $sharedConfDir = $ENV{'SIM_SHAREDCONFD'} || die "Oops no env found for SIM_SHAREDCONFD.";


sub printMainMenu {
  my $fontColor = "#222222";
  print("<TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR><TD BGCOLOR=#EEEEEE><CENTER>
    <A HREF=$httpScriptName?$module+$tool+imIpDatabase><FONT COLOR=$fontColor>ipDatabase</FONT></A> 
    </TD></TR></TABLE><CENTER>
        ");
}

sub importIpDatabase {
  my $fileName = param('fileName');
  if ( $fileName eq "" ) {
    print("<FORM method=post Action=$httpScriptName?$module+$tool+imIpDatabase ENCTYPE=\"multipart/form-data\">
               <INPUT NAME=\"fileName\" Size=60 TYPE=file>
               <INPUT TYPE=submit Value=\"Upload file\">
             </FORM>");
  } else {
    $fileName =~ s/.*[\/\\](.*)/$1/;
    print("Uploading file $fileName.<BR>\n");
    my $upload_filehandle = upload('fileName');
    my $shortName = "upload.$$";
    my $uploadFile = "$SIMparam{'SIMtmpDir'}/$shortName";
    open( UPLOADFILE, ">$uploadFile" ) || die "Oops, cluld not create upload file.";
    while ( <$upload_filehandle> ) {
      print UPLOADFILE;
    }
    close UPLOADFILE;
    print("Created $uploadFile.<HR>");
    open( IN, $uploadFile );
    my @lines = <IN>;
    close IN;
    my @recType;
    print("<TABLE>");
    my $num = 0;
    my $testNum;
    foreach my $entry (@lines) {
      chomp $entry;
      $entry =~ s/\"//g;
      @recType = split(';', $entry);
      if ( $num eq 0 ) {
        print("Searching colum test");
        my $eNum = 0;
        foreach my $var (@recType) {
          # strip white space from reccord names.
          $var =~ s/\s+//g;
#         print("$eNum=\"$var\" ");
          if ( $var eq "var\:test" ) {
            $testNum = $eNum;
            print(", found");
          }
          $eNum++;
        }
      }
      my $line = join('</TD><TD>', @recType);
      my $bgColor;
      my $testInfo;
      # strip white space from the test reccord (sometimes added by Excell / Calc).
      $recType[$testNum] =~ s/\s+//g;
      if ( $num eq 0 ) {
        $bgColor = "#DDDDDD";
      } elsif ( $testNum eq "" ) {
        $bgColor = "yellow";
      } elsif (( $recType[$testNum] eq ",testValue" ) or ( $recType[$testNum] eq "testValue" )) {
        $bgColor = "#33ff77";
      } else {
        $bgColor = "#cc3333";
        $testInfo = "\"$recType[$testNum]\"";
      }
      print("<TR BGCOLOR=$bgColor><TD ALIGN=right>$testInfo $num</TD><TD>$line</TD></TR>");
      $num++;
    }
    print("</TABLE> After verification run: 
    <A HREF=$httpScriptName?$module+$tool+runIpImport+$shortName>Import $shortName</A> 
          ");
  }
}

sub runIpImport {
  my $fileName = "@_[0]";
  my $uploadFile = "$SIMparam{'SIMtmpDir'}/$fileName";
  if ( -f $uploadFile ) {
    open( IN, $uploadFile );
    my @lines = <IN>;
    close IN;
    my @recType;
    my $testNum;
    foreach my $entry (@lines) {
      #split on ,
      $entry =~ s/\"//g;
      if ( $recType[0] eq "" ) {
        my $num = 0;
        # strip white space from reccord names.
        $entry =~ s/\s+//g;
#       @recType = split('\",\"', $entry);
        @recType = split(';', $entry);
        foreach my $entry (@recType) {
          $entry =~ s/\"//g;
          $recType[$num] = $entry;
          if ( $entry eq "var:test" ) {
            $testNum = $num;
            print("Found test on $testNum");
          }
          $num++;
        }
      } elsif ( $testNum eq "" ) {
        print("No test entry found for this import yet.<BR>");
      } else {
        my ( $ipAddr, $ipDir );
#       my @varInfo = split('\",\"', $entry);
        my @varInfo = split(';', $entry);
        # strip the white space arround reccords (sometimes added by excell / calc)
        $varInfo[$testNum] =~ s/\s+//g;
        if (( $varInfo[$testNum] ne ",testValue" ) and ( $varInfo[$testNum] ne "testValue" )) {
          print(" skipping line \"$entry\", no test entry found.<BR>.");
        } else {
          my $num = 0;
          print("</CENTER>\n");
          foreach my $entry (@recType) {
#           $varInfo[$num] =~ s/\"//g;
            printDebug(0, "$entry = \"$varInfo[$num]\"");
            my ( $type, $name ) = split(':', $entry);
            if ( $varInfo[$num] eq "" ) {
              print(" skip, empty ");
            } elsif ( $type eq "var" ) {
              if ( $name eq "ipAddr" ) {
                $ipAddr = $varInfo[$num];
                my $test = testIfIp( $ipAddr );
                if ( "$test" eq "oke" ) {
                  $ipDir = getIpDir( $ipAddr );
                  if ( ! -d $ipDir ) {
                    printDebug(0, "Adding node $ipAddr. ");
                    addIpNode( $ipAddr, "import-$remoteUser" );
                  }
                }
              } elsif ( $name eq "hwName" ) {
                if ( $ipAddr ne "" ) {    
                  my $hwName = testDnsName($varInfo[$num]);
                  print(" ipDir = $ipDir ");
                  updField( $ipAddr, "import-$remoteUser", "Hardware name", "$ipDir/hwName", $hwName );
                }
              }
            } elsif ( $type eq "ip" ) {
              if (( -d $ipDir ) and ( $ipDir ne "" )) {    
                updField( $ipAddr, "import-$remoteUser", "Field: $type, $name", "$ipDir/$name", $varInfo[$num] );
              } else {
                print(" skip, ipDir=$ipDir.");
              }
            } elsif ( $type eq "dev" ) {
              if ( $ipAddr eq "" ) {
                print("No ipaddr found for $type, $name, $varInfo[$num].");
              } elsif ( -f "$ipDir/hostname.txt" ) {
                my $devDir = getDevDir( $ipAddr );
                if ( ! -d $devDir ) {
                  print("No device directory found for $ipAddr.");
                } else {
                  updField( $ipAddr, "import-$remoteUser", "Field: $type, $name", "$devDir/$name", $varInfo[$num] );
                }
              }
            } elsif ( $type eq "hw" ) {
              if ( $ipAddr eq "" ) {
                print("No ipaddr found for $type, $name, $varInfo[$num].");
              } elsif ( -f "$ipDir/hwName" ) {
                my $hwName = catFileLine( "$ipDir/hwName" );
                my $hwDir = "$SIMparam{'SIMhardwareInfoDir'}/$hwName";
                testMkDir("$SIMparam{'SIMhardwareInfoDir'}/$hwName");
                my $hwFile = "$SIMparam{'SIMhardwareInfoDir'}/$hwName/$name";
                print(" hwFile: $hwFile. ");
                updField( $ipAddr, "import-$remoteUser", "Field: $type, $name", "$hwFile", $varInfo[$num] );
              } else {
                print("No hwName found for $ipAddr.");
              }
            }
          $num++;
          }
        }
        print("<HR>");
      }
    }
  }
}
# ------------------------------------- Main ---------------------------------------

printMainMenu;
if ( "$action" eq "imIpDatabase" ) {
  importIpDatabase;
} elsif ( "$action" eq "runIpImport" ) {
  runIpImport( $option1 );
} else {
  print("Select an option from the above menu.");
}
#printFooter;
